<template>
  <el-dialog
    v-if="visible"
    v-el-drag-dialog
    :title="title"
    :visible.sync="visible"
    width="1350px"
    @closed="reset"
  >
    <div class="add_price_main">
      <div style="width: 50%;">
        <div class="border">
          <el-form ref="dataForm" class="form" :model="temp" label-position="right" label-width="80px">
            <el-form-item v-if="title==='客户模式调价'" label-width="0" prop="csmPhone">
              <el-input v-model.trim="temp.text" placeholder="请输入">
                <el-select slot="prepend" v-model="temp.type" style="width: 100px;" placeholder="请选择">
                  <!-- <el-option label="客户电话" :value="'csmRgPhone'" /> -->
                  <el-option label="身份证号" :value="'sfzh'" />
                  <el-option label="客户编号" :value="'csmCode'" />
                </el-select>
                <el-button slot="append" class="append-search" @click="searchCms">查询</el-button>
              </el-input>
            </el-form-item>
            <el-form-item v-if="title==='客户模式调价' && magShow" label-width="20px"><span style="color: red;">{{ magText }}</span></el-form-item>
          </el-form>
          <p style="display: flex; margin: 20px 0;">
            <span class="info" :title="csmInfo.csmCode" style="width: 40%;">客户编号：{{ csmInfo.csmCode }}  </span>
            <span class="info" :title="csmInfo.csmName" style="width: 30%;">客户名称：{{ csmInfo.csmName }}  </span>
            <span class="info" :title="csmInfo.csmRgPhone" style="width: 30%;">客户电话：{{ csmInfo.csmRgPhone }}  </span>
          </p>
          <p style="display: flex; margin-top: 18px;">
            <span class="info" :title="csmInfo.sfzh" style="width: 40%;">身份证号：{{ csmInfo.sfzh }}   </span>
            <span class="info" :title="csmInfo.csmRgAddress" style="width: 60%;">客户地址：{{ csmInfo.csmRgAddress }}   </span>
          </p>
        </div>

        <!-- 左下部分 -->
        <div class="border" style="width: 100%; margin-top: 10px;">
          <div style="display: flex; margin: 10px 0;">
            <p style="margin-right: 5px;">当前特价信息</p>
            <div>
              <el-radio v-model="expired" label="2">未过期</el-radio>
              <el-radio v-model="expired" label="1">过期</el-radio>
            </div>
          </div>
          <lb-table
            ref="lbTable_left"
            v-loading="$loadingPlugin.fetchData"
            border
            element-loading-text="加载中"
            :column="column"
            :data="tableDataLeft.data"
            highlight-current-row
            :total="tableDataLeft.total"
            custom-column
            height="300"
            @expand-change="expandChange"
            @current-change="selectLeftTable"
          />
        </div>
      </div>
      <div class="border" style="width: 50%; margin-left: 10px;">
        <el-form ref="dataFormRight" class="form_right" :model="shop" label-position="right" label-width="80px">
          <el-form-item label="商品分类:" prop="orgSNNo">
            <el-tree-select
              ref="treeSelect"
              v-model="shop.gtId"
              :disabled="editMode"
              :clearable="false"
              class="tree-select"
              :popover-width="360"
              :select-params="{
                clearable: true,
                placeholder: '请选择',
                loading: $loadingPlugin.getTreeData
              }"
              :tree-params=" {
                filterable:true,
                'expand-on-click-node': false,
                'highlight-current': true,
                'filterable': true,
                props:{
                  value:'gtId',
                  label: 'gtName',
                  disabled: 'disabled',
                },
                data: treeData
              }"
              @node-click="selectTreeChange"
              @search-clear="searchClear"
            />
          </el-form-item>
          <el-form-item label="商品名称:" class="merge-item">
            <el-select v-model="shop.goodsId" :disabled="editMode" style="width: 170px; margin-right: 2px;" filterable clearable>
              <!-- <el-option v-for="(l,i) in goodsTypesDetailList" :key="l.gtId" :value="l.goodsId" :label="l.goodsName" /> -->
              <el-option v-for="(l,i) in goodsTypesDetailList" :key="i" :value="l.goodsId" :label="l.goodsName" />
            </el-select>
          </el-form-item>
          <el-form-item style="width: 20%;" label="" label-width="0" class="merge-item">
            <el-button v-if="!editMode" type="primary" icon="" :loading="$loadingPlugin.exportFile" @click="addShop">添加</el-button>
            <el-button v-if="editMode" type="primary" icon="" :loading="$loadingPlugin.exportFile" @click="deEditMode">取消编辑</el-button>
          </el-form-item>
        </el-form>
        <lb-table
          ref="tableData_right"
          v-loading="$loadingPlugin.fetchData"
          border
          stripe
          element-loading-text="加载中"
          :column="tableDataRight.column"
          :data="tableDataRight.data"
          highlight-current-row
          :total="tableDataRight.total"
          custom-column
          height="150"
          @fetch="fetchDataLeft"
        />
        <el-form v-if="scope===1" class="checkRidio" label-width="90px;" style="margin-top: 10px;">
          <el-form-item style="display: flex; align-items: center; width: 100%;" label-width="100px" label="远距配送费:" class="merge-item">
            <el-radio v-model="radio.spFee" :label="1">市场价</el-radio>
            <el-radio v-model="radio.spFee" :label="2">自定义</el-radio>
            <el-input-number v-if="radio.spFee===2" v-model="price.spFee" :controls="false" :min="0" :max="10000" :precision="2" size="mini" placeholder="请输入远距配送费" />
          </el-form-item>
          <el-form-item style="display: flex; align-items: center; width: 100%;" label-width="90px" label="上楼费:" class="merge-item">
            <el-radio v-model="radio.lpFee" :label="1">市场价</el-radio>
            <el-radio v-model="radio.lpFee" :label="2">自定义</el-radio>
          </el-form-item>
          <el-form-item v-if="radio.lpFee===2" label-width="90px">
            <div style="display: flex;">
              <p style="margin-right: 10px;">上楼费基数(起步价): </p>
              <el-input-number v-if="radio.lpFee===2" v-model="price.baseFloorFee" :controls="false" :min="0" :max="10000" :precision="2" style="width: 100px;" size="mini" placeholder="起步价" />
              <p style="margin-right: 10px; margin-left: 10px;">楼层费: </p>
              <el-input-number v-if="radio.lpFee===2" v-model="price.lpFee" :controls="false" :min="0" :max="10000" :precision="2" style="width: 100px;" size="mini" placeholder="楼层费" />
            </div>
          </el-form-item>
          <el-form-item style="display: flex; align-items: center; width: 100%;" label-width="90px" label="服务费:" class="merge-item">
            <el-radio v-model="radio.tpFee" :label="1">市场价</el-radio>
            <el-radio v-model="radio.tpFee" :label="2">自定义</el-radio>
            <el-input-number v-if="radio.tpFee===2" v-model="price.tpFee" :controls="false" :min="0" :max="10000" :precision="2" size="mini" placeholder="请输入服务费" />
          </el-form-item>
        </el-form>
        <el-form label-width="90px;" style="margin-top: 10px;">
          <el-form-item label-width="90px" style="width: 100%;" label="时效范围:" class="merge-item">
            <el-date-picker
              v-model="submit.date"
              style="width: 100%;"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item>
          <el-form-item label-width="90px" style="width: 100%;" label="生效机构:" prop="orgSNNo">
            <el-tree-select
              ref="sysTree"
              v-model="submit.orgSNNo"
              :clearable="false"
              :disabled="submit.orgSNNo && curType === 'edit'"
              class="tree-select"
              :popover-width="360"
              :select-params="{
                clearable: true,
                placeholder: '请选择组织机构',
                loading: $loadingPlugin.getTreeData
              }"
              :tree-params=" {
                filterable:true,
                'expand-on-click-node': false,
                'highlight-current': true,
                props:{
                  value:'orgSNNo',
                  label: 'orgName',
                  disabled: 'disabled',
                },
                data: treeOrgData
              }"
              @node-click="selectOrgTreeChange"
              @search-clear="searchClear"
            />
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">
        关闭
      </el-button>
      <el-button v-if="isShowBtn" :loading="$loadingPlugin.add || $loadingPlugin.edit" type="primary" @click="success">
        提交调价
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { querySpecialPriceCsmWin, CmsSpecialSearchCsmInfo, CmsSpecialPriInfo, goodsTypeDetail, goodsTypeQueryAllList, CmsSpecialKeyWords, CmsSpecialDeleteGoods, CmsSpecialCsmInfoAddEdit, CmsSpecialconfigUpdateDetail } from '@/api'
  import { parseTime } from '@/utils'
  import getTreeData from '@/utils/jsonTree'
  import dayjs from 'dayjs'
  export default {
    name: 'addprice',
    props: ['treeOrgData', 'parentFetchData'],
    data() {
      return {
        scope: 0, // 判断是否显示服务费等
        detailList: [],
        curType: 'add',
        visible: false,
        title: '客户模式调价',
        magText: '',
        magShow: false,
        isShowBtn: true,
        radio: {
          spFee: 1, // 配送
          lpFee: 1, // 上楼
          tpFee: 1 // 服务
        },
        price: {
          spFee: undefined, // 配送
          lpFee: undefined, // 上楼
          tpFee: undefined, // 服务
          baseFloorFee: undefined // 起步价
        },
        submit: {
          date: []
        },
        selectOrgData: {}, // 当前选择的机构信息
        csmInfo: {},
        treeData: [],
        editMode: false,
        goodsTypesDetailList: [],
        keyWordsList: [],
        priceTypeMap: [{ 'value': 1, 'desc': '下浮', 'key': 'Fluctuating' }, { 'value': 2, 'desc': '固定', 'key': 'Fixed' }],
        expired: '2',
        temp: {
          type: 'sfzh',
          text: '',
          csmId: ''
        },
        shop: {
          gtId: '',
          goodsId: ''
        },
        cols: [
          {
            prop: 'createTime',
            label: '操作时间',
            render: (h, { row }) => <span>{ row.createTime && parseTime(row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
          },
          {
            prop: 'createUser',
            label: '操作员'
          },
          {
            prop: 'goodsName',
            label: '商品名称'
          },
          {
            prop: 'remark',
            label: '状态',
            render: (h, { row }) => <span>{ row.remark && row.remark + '商品' }</span>
          },
          {
            prop: 'priceType',
            label: '波动方式',
            render: (h, { row }) => <span>{ row.priceType && this.priceTypeMap.find(l => l.value === row.priceType).desc }</span>
          },
          {
            prop: 'price',
            label: '波动价格',
            render: (h, { row, $index, column }) => <span>{ row[column.property] ? (row[column.property] * 1).toFixed(2) : '' }</span>
          },
          {
            prop: 'startDt',
            label: '时效范围',
            render: (h, { row }) => <span>{ (row.startDt && row.endDt) && parseTime(row.startDt, '{y}-{m}-{d} {h}:{i}:{s}') + '~' + parseTime(row.endDt, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
          },
          {
            prop: 'scopeOrgName',
            label: '生效机构'
          }
        ],
        tableDataLeft: {
          data: []
        },
        tableDataRight: {
          total: 0,
          column: [
            { label: '商品名称', prop: 'goodsName', width: 150, align: 'center' },
            { label: '波动方式', prop: 'priceType', width: 123, align: 'center',
              render: (h, { row, $index, column }) => {
                return (
                <div>
                  {row._edit ? (
                    <el-select size='mini' value={row[column.property]} style='width: 100px' onChange={(val) => { this.changePriceType(row, $index, column, val) }}>
                      {this.priceTypeMap.map((l) => {
                        return (
                          <el-option size='mini' label={l.desc} value={l.value}></el-option>
                        )
                      })}
                    </el-select>
                  ) : (<span>{row.priceType && this.priceTypeMap.find(l => l.value === row.priceType).desc }</span>)}
                </div>
              )
              }
            },

            { label: '波动价格', prop: 'price', width: 123, align: 'center',
              render: (h, { row, $index, column }) => {
                return (
                <div>
                  {row._edit ? (
                    <el-input size='mini' value={row[column.property] } style='width: 100px' onInput={(val) => { this.changeInput(row, column, val) }}> </el-input>
                  ) : (<span >{row[column.property] ? (row[column.property] * 1).toFixed(2) : ''}</span>)}
                </div>
              )
              }
            },
            { label: '关键字', prop: 'keyId', width: 123, align: 'center',
              render: (h, { row, $index, column }) => {
                return (
                <div>
                  {row._edit ? (
                    <el-select size='mini' value={row[column.property]} style='width: 100px' onChange={(val) => { this.changePriceType(row, $index, column, val) }}>
                      {this.keyWordsList.map((l) => {
                        return (
                          <el-option size='mini' label={l.keyName} value={l.keyId}></el-option>
                        )
                      })}
                    </el-select>
                  ) : (<span>{row.keyId && this.keyWordsList.find(l => l.keyId === row.keyId).keyName ? this.keyWordsList.find(l => l.keyId === row.keyId).keyName : '' }</span>)}
                </div>
              )
              }
            },
            { label: '操作', prop: 'op', width: '', align: 'left',
              render: (h, { row, $index }) => {
                return (
                 <div>
                    <el-link size='mini' onClick={() => this.handleEdit(row)}>
                      {row._edit ? '' : '编辑'}
                    </el-link>
                    <el-link size='mini' onClick={() => this.handleSave(row) } >
                      {row._edit ? '保存' : ''}
                    </el-link>
                  <span onClick={() => { this.delShop(row, $index) }} style='color:red;cursor: pointer'>{this.editMode ? '' : 'X'}</span>
                  </div>
                )
              }
            }
          ],
          data: []
        }
      }
    },
    computed: {
      column: function() {
        return [
          {
            type: 'expand',
            render: (h, { row, $index, column }) => {
              return (
                <div>
                 {this.detailList[row.categoryDetailId] && this.detailList[row.categoryDetailId].map(item => {
                   return <div class='detail-marge'>
                    <span>【{ item.createTime && this.formatDate(item.createTime) }】</span>
                    <span>操作员【{ item.createUser}】</span>
                    <span>{item.remark}商品【{ item.goodsName}】的报价</span>
                    <span>【波动方式：{item.priceType && this.priceTypeMap.find(l => l.value === item.priceType).desc};波动价格：{ item.price ? (item.price * 1).toFixed(2) : '0.00'}元；时效范围：{(item.startDt && item.endDt) && this.formatDate(item.startDt) + '~' + this.formatDate(item.endDt) }生效机构：{item.scopeOrgName} 】</span>
                   </div>
                 })}
                </div>
                /**
                 <lb-table
                    ref='lbTable'
                    border
                    element-loading-text='加载中'
                    column={this.cols}
                    data={row.detailList}
                    pagination={false}
                  />
                </div>*/
              )
            }
          },
          { label: '商品名称', prop: 'goodsName', width: 123, align: 'center' },
          { label: '波动方式', prop: 'priceType', width: 80, align: 'center',
            render: (h, { row }) => <span>{row.priceType && this.priceTypeMap.find(l => l.value === row.priceType).desc }</span>
          },
          { label: '波动价格', prop: 'price', width: 80, align: 'right',
            render: (h, { row, column }) => <span>{row.price && row.price.toFixed(2) }</span>
          },
          { label: '时效范围', prop: 'time', width: 240, align: 'center',
            render: (h, { row, column }) => <span>{this.timeformat(row, column) }</span>
          },
          { label: '状态', prop: 'checkStatus', width: 90, align: 'center',
            render: (h, { row, column }) => <span>{this.statusMap(row, column) }</span>
          },
          { label: '生效机构', prop: 'scopeOrgName', width: 220, align: 'left' },
          { label: '操作', prop: 'op', width: 60, align: 'center',
            render: (h, { row, column }) => <span onClick={() => { this.del(row) }} style='color:red;cursor: pointer'>删除</span>
          }
        ]
      }
    },
    watch: {
      'radio.spFee': {
        async handler(newVal, oldVal) {
          // console.log(newVal, oldVal)
          if (newVal === 1) {
            this.price.spFee = 0
          }
        },
        deep: true,
        immediate: true
      },
      'radio.lpFee': {
        async handler(newVal, oldVal) {
          // console.log(newVal, oldVal)
          if (newVal === 1) {
            this.price.lpFee = 0
            this.price.baseFloorFee = 0
          }
        },
        deep: true,
        immediate: true
      },
      'radio.tpFee': {
        async handler(newVal, oldVal) {
          // console.log(newVal, oldVal)
          if (newVal === 1) {
            this.price.tpFee = 0
          }
        },
        deep: true,
        immediate: true
      }
    },
    async created() {
      await this.getTreeData()
      this.getKeyWords()
    },
    mounted() {
      this.$watch('expired', () => {
        if (this.csmInfo.csmId) {
          this.deEditMode()
          this.fetchDataLeft()
        }
      })
    },
    methods: {
      async open(temp) {
        this.reset()
        await this.getWinData()
        this.curType = temp ? 'edit' : 'add'
        this.temp.csmId = temp && temp.csmId
        this.submit.date = [dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss'), '']
        this.visible = true
        if (temp) {
          // console.log({ ...temp }, 'open')
          this.title = '客户编辑调价'
          this.searchCms(temp.csmCode)
        } else {
          this.title = '客户模式调价'
        }
        // 新增时添加商品分类默认值
        if (this.treeData.length > 0 && this.curType === 'add') {
          this.shop.gtId = this.treeData[0].gtId
          this.getGoodsTypeDetails(this.shop.gtId)
        } else {
          this.shop.gtId = ''
        }
      },
      async getWinData() {
        const res = await querySpecialPriceCsmWin({
          csmCode: ''
        })
        this.scope = res.data.scope
      },
      // 选择行时上楼费服务费转译
      changePrice(row) {
        if (row.spFee && parseFloat(row.spFee * 1).toString() !== 'NaN') {
          this.radio.spFee = 2
          this.price.spFee = ((row.spFee >> 1) / 100).toFixed(2)
        } else {
          this.radio.spFee = 1
          this.price.spFee = ''
        }
        if (row.lpFee && parseFloat(row.lpFee * 1).toString() !== 'NaN') {
          this.radio.lpFee = 2
          this.price.lpFee = ((row.lpFee >> 1) / 100).toFixed(2)
        } else {
          this.radio.lpFee = 1
          this.price.lpFee = ''
        }
        if (row.tpFee && parseFloat(row.tpFee * 1).toString() !== 'NaN') {
          this.radio.tpFee = 2
          this.price.tpFee = ((row.tpFee >> 1) / 100).toFixed(2)
        } else {
          this.radio.tpFee = 1
          this.price.tpFee = ''
        }
        if (row.baseFloorFee && parseFloat(row.baseFloorFee * 1).toString() !== 'NaN') {
          this.radio.lpFee = 2
          this.price.baseFloorFee = (row.baseFloorFee * 1).toFixed(2)
        } else {
          this.price.baseFloorFee = ''
        }
      },
      // 编辑模式
      async  selectLeftTable(row) {
        if (JSON.stringify(row) === '{}' || !row) {
          return
        }
        // 已过期订单不可编辑
        if (Date.parse(row.endDt) < new Date()) {
          this.$message({
            type: 'warning',
            message: '已失效不可编辑'
          })
          return
        }

        await this.getGoodsTypeDetails(row.gtId)
        this.editMode = true
        console.log({ ...row }, '选择当前行')
        this.changePrice(row) // // 选择行时上楼费服务费转译
        this.shop = { ...row, data: [] }
        var date = [row.startDt, row.endDt]
        this.submit.date = date
        this.submit.orgSNNo = row.orgSNNo
        this.selectOrgTreeChange(row)
        this.tableDataRight.data = [{ ...row }]
        // gtId
      },
      // 取消编辑模式
      deEditMode() {
        this.editMode = false
        this.tableDataRight.data = []
        this.$refs.lbTable_left.setCurrentRow({})
      },
      async success() {
        if (!this.rule()) {
          return
        }
        const list = [...this.tableDataRight.data]
        // 价格转为二进制提交
        var submitPrice = { ...this.price }
        // console.log('submitPrice', submitPrice)

        var priceCategoryDetailInfoList = list.map(item => {
          return { ...item, ...submitPrice, ...this.selectOrgData, startDt: this.submit.date[0], endDt: this.submit.date[1] }
        })
        const params = {
          csmCode: this.csmInfo.csmCode,
          priceCategoryDetailInfoList
        }
        const res = await CmsSpecialCsmInfoAddEdit(params)
        if (res.success) {
          this.$message.success('提交成功')
          this.visible = false

          if (this.title === '客户模式调价') {
            this.searchCms()
            return
          }
          this.parentFetchData({})
          this.reset()
        }
      },
      rule() {
        var flag = false
        if (!this.csmInfo.csmCode) {
          this.$message.error('未获取到用户信息')
          return flag
        }
        if (!this.submit.date || !this.submit.date[0] || !this.submit.date[1]) {
          this.$message.error('请选择时效范围')
          return flag
        }
        if (!this.submit.orgSNNo) {
          this.$message.error('请选择生效机构')
          return flag
        }
        if (!this.tableDataRight.data.length) {
          this.$message.error('请添加需要调价的商品')
          return flag
        }
        for (var i = 0; i < this.tableDataRight.data.length; i++) {
          var l = this.tableDataRight.data[i]
          if (!l.priceType) {
            this.$message.error(`${l.goodsName}没有选择波动方式，不可提交`)
            return flag
          }
          if (!l.price) {
            this.$message.error(`${l.goodsName}没有选择波动价格，不可提交`)
            return flag
          } else {
            const reg = /^(-?\d+)(\.\d+)?$/
            // console.log(value)
            console.log(reg.test(l.price))
            if (!reg.test(l.price)) {
              this.$message.error('波动价格输入有误,请输入数字或小数')
              return flag
            }
          }
        }
        for (var value in this.radio) {
          var item = this.radio[value]
          if (item === 2 && !this.price[value] && this.price[value] !== 0) {
            switch (value) {
            case 'spFee': this.$message.error('您选择自定义远距配送费却没有输入具体的值,请输入')
                          break
            case 'tpFee': this.$message.error('您已选择自定义服务费却没有输入具体的值,请输入')
                          break
            case 'lpFee': this.$message.error('您选择自定义上楼费却没有输入具体的值,请输入')
                          break
            }
            return flag
            // break
          }
          if (item === 2) {
            this.price[value] *= 100
            this.price[value] = Number(this.price[value].toFixed(0))
            this.price[value] = (this.price[value] << 1) | 1
            this.price.baseFloorFee = this.price.baseFloorFee * 1 || 0
          }
          if (item === 1) {
            this.price[value] = 0
          }
        }
        // console.log(flag)
        flag = true
        return flag
      },
      // 列表行详情
      async expandChange(row) {
        const res = await CmsSpecialconfigUpdateDetail({
          categoryDetailId: row.categoryDetailId,
          csmId: row.csmId,
          pageSize: 10
        })
        this.$set(this.detailList, row.categoryDetailId, [])
        this.$set(this.detailList, row.categoryDetailId, res.data)
      },
      async  searchCms(data = '') {
        // csmInfo
        const params = { csmStatus: 2 }
        if (this.title === '客户模式调价') {
          params[this.temp.type] = this.temp.text
        } else if (this.title === '客户编辑调价') {
          params['csmCode'] = data
          params['csmStatus'] = -2
        }
        console.log(params)
        if (!this.temp.text && this.title === '客户模式调价') {
          this.$message.warning('查询条件不能为空')
          return
        }
        try {
          const res = await CmsSpecialSearchCsmInfo(params)
          // console.log(res.data, 'data')
          if (res.data) {
            this.csmInfo = res.data
            // 处理按钮逻辑
            const arr = [-1, 1, 3]
            if (arr.includes(this.csmInfo.csmStatus)) {
              // 隐藏按钮
              const obj = {
                '-1': '已注销',
                '1': '未审核',
                '3': '已挂失'
              }
              this.magText = `当前客户${obj[String(this.csmInfo.csmStatus)]}`
              this.magShow = true
              this.isShowBtn = false
            } else {
              // 显示按钮
              this.isShowBtn = true
              this.magShow = false
            }
            await this.fetchDataLeft()
          } else {
            this.csmInfo = {}
            this.tableDataLeft.data = []
            this.$message.error('客户资料未找到，可能原因已被删除')
          }
          // console.log(res)
        } catch (e) {
          console.log(e)
        }
      },

      async fetchDataLeft() {
        if (JSON.stringify(this.csmInfo) === '{}') {
          return
        }
        var params = {
          pageIndex: 1,
          pageSize: 0,
          expired: this.expired,
          csmId: this.curType === 'edit' ? this.temp.csmId : this.csmInfo.csmId
        }
        const res = await CmsSpecialPriInfo(params)
        this.tableDataLeft.data = res.data.rows.map(l => {
          return { ...l, detailList: [] }
        })
        // if (currentPage === 1) this.tableData.total = res.data.total
      },
      // 选择商品分类
      async selectTreeChange(value) {
        // this.orgSNNo = value.orgSNNo
        this.shop.goodsId = ''
        if (value) {
          await this.getGoodsTypeDetails(value.gtId)
        }
      },
      // 获取商品分类详情
      async getGoodsTypeDetails(val) {
        try {
          const res = await goodsTypeDetail({ gtId: val })
          this.goodsTypesDetailList = res.data.rows
          // console.log(res)
        } catch (error) {
          console.log(error)
        }
      },
      // 获取商品分类树
      async getTreeData() {
        const res = await goodsTypeQueryAllList({})
        const data = res.data.filter(item => item.gtCategory === 1).map(item => ({
          label: item.gtName,
          ...item
        }))
        this.treeData = getTreeData(data, 'parentId', 'gtId')
        // 新增时添加商品分类默认值
        if (this.treeData.length > 0 && this.curType === 'add') {
          this.shop.gtId = this.treeData[0].gtId
          this.getGoodsTypeDetails(this.shop.gtId)
        } else {
          this.shop.gtId = ''
        }
      },
      // 添加商品
      addShop() {
        if (!this.shop.gtId || !this.shop.goodsId) {
          this.$message.error('请选择商品')
          return
        }
        // console.log({ ...this.shop })
        var goodsName = this.goodsTypesDetailList.find(l => l.goodsId === this.shop.goodsId).goodsName
        // console.log(goodsName)
        this.tableDataRight.data.push({ ...this.shop, price: '', goodsName })

        // console.log(this.shop, 'this.shop')
        // console.log(this.tableDataRight.data, 'this.tableDataRight.data')
      },
      handleEdit(row, $index) {
        this.$set(row, '_edit', true)
      },
      handleSave(row, $index) {
        // const reg = /^(-?\d+)(\.\d+)?$/
        // if (!reg.test(row.discount)) {
        //   this.$message.warning('权益数值只能为数值')
        //   return
        // }
        // if (!reg.test(row.disLimit)) {
        //   this.$message.warning('优惠上限只能为数值')
        //   return
        // }
        this.$set(row, '_edit', false)
        this.$set(this.tableDataRight.data, $index, JSON.parse(JSON.stringify(row)))
      },
      // 波动方式选择事件
      changePriceType(row, $index, column, value) {
        console.log(value)
        // var text = event.target.innerText
        // console.log(event)
        row[column.property] = value
        this.$set(this.tableDataRight.data, $index, JSON.parse(JSON.stringify(row)))
        this.tableDataRight.data = [...this.tableDataRight.data]
      },
      // 商品分类的onchange事件
      changeGoodsType(row, column, value) {
        // console.log(value)
        var text = event.target.innerText
        row[column.property] = text
        this.tableData.data = [...this.tableData.data]
        this.getGoodsTypeDetails(value)
      },
      // 波动价格input事件
      changeInput(row, column, value) {
        row[column.property] = value
        // const reg = /^(-?\d+)(\.\d+)?$/
        // console.log(value)
        // console.log(reg.test(value))
        // if (reg.test(value)) {
        //   row[column.property] = value
        //   // this.tableData.data = [...this.tableData.data]
        // } else {
        //   row[column.property] = value

        //   // row[column.property] = ''
        // }
      },
      // 状态文本格式化
      statusMap(row, column) {
        if (row.endDt < row.nowDt) {
          return '已失效'
        }
        const val = row[column.property]
        if (val === 0) {
          return '一级待审'
        } else if (val === 1) {
          return '二级待审'
        } else if (val === 2) {
          return '已生效'
        } else if (val === 4) {
          return '已驳回'
        }
        return ''
      },
      // 时间格式化
      timeformat(row, column) {
        const startTime = parseTime(row.startDt, '{y}:{m}:{d} {h}:{i}:{s}')
        const endTime = parseTime(row.endDt, '{y}:{m}:{d} {h}:{i}:{s}')
        return `${startTime}至${endTime}`
      },
      formatDate(time) {
        const date = new Date(time)
        date.setHours(date.getHours() - 8)
        return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
      },
      // 本地删除商品
      delShop(row, index) {
        this.tableDataRight.data.splice(index, 1)
        // console.log(row)
      },
      // 删除商品
      del(row) {
        // console.log(event)
        if (event && event.stopPropagation) {
          event.stopPropagation()
        // 因此它支持W3C的stopPropagation()方法
        } else {
          // 否则，我们需要使用IE的方式来取消事件冒泡
          window.event.cancelBubble = true
        }

        // event.stopPropagation()
        const vm = this
        this.$confirm(`确定要删除吗？`, '提示', {
          type: 'info'
        }).then(() => {
          var params = {
            categoryDetailId: row.categoryDetailId,
            csmId: vm.csmInfo.csmId,
            priceCgId: row.priceCgId
          }
          try {
            // console.log(params)
            CmsSpecialDeleteGoods(params).then(data => {
              this.fetchDataLeft()
            })
          } catch (e) {
            console.log(e)
          }
        })
      },
      async getKeyWords() {
        const params = {
          currentPage: 1,
          pageSize: 20
        }
        try {
          const res = await CmsSpecialKeyWords(params)
          this.keyWordsList = res.data.rows.filter(l => l.keyStatus !== -1)
          // console.log(res)
        } catch (e) {
          console.log(e)
        }
      },
      // 选择生效机构
      selectOrgTreeChange(value) {
        // console.log(value)
        // this.orgSNNo = value.orgSNNo
        this.selectOrgData = { orgSNNo: value.orgSNNo, orgName: value.orgName, orgId: value.orgId }
      },
      async add() {

      },
      async edit() {

      },
      reset() {
        this.magShow = false
        this.temp.text = ''
        this.isShowBtn = true
        this.csmInfo = {}
        this.shop = {
          gtId: '',
          goodsId: ''
        }
        this.tableDataLeft.data = []
        this.tableDataRight.data = []
        this.submit = {
          date: []
        }
        this.price = {
          spFee: undefined, // 配送
          lpFee: undefined, // 上楼
          tpFee: undefined, // 服务
          baseFloorFee: undefined // 起步价
        }
        this.radio = {
          spFee: 1, // 配送
          lpFee: 1, // 上楼
          tpFee: 1 // 服务
        }
        this.editMode = false
        this.expired = '2'
      },
      searchClear() {
        if (this.$refs.treeSelect) this.$refs.treeSelect.keywords = ''
        if (this.$refs.sysTree) this.$refs.sysTree.keywords = ''
      }
    }
  }
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  flex-wrap: wrap;
  & /deep/ .el-form-item {
    padding-right: 10px;
    .el-form-item__content > .el-select {
      width: 100%;
    }
  }
}
.form_right {
  display: flex;
  flex-wrap: wrap;
  & /deep/ .el-form-item {
    width: 40%;
    padding-right: 10px;
    .el-form-item__content > .el-select {
      width: 100%;
    }
  }
}
.add_price_main {
  display: flex;
  .info {
    display: inline-block;
    overflow: hidden;
    // font-size: 12px;
    color: #999;
    text-overflow: ellipsis;
    white-space: nowrap;
    vertical-align: bottom;
  }
  .border {
    padding: 15px 5px;
    border: 1px solid #ebeff6;
  }
}
.checkRidio {
  /deep/ .merge-item .el-form-item__content {
    align-items: center;
    margin-left: 5px !important;
  }
}
/deep/.detail-marge {
  margin-bottom: 8px;
}
</style>
